<?php
class InfoController extends AppController {
    var $helpers = array ('Html','Form','Session');
    var $name = 'Info'; // riferimento alla cartella delle view
    //var $modelClass = 'Multa';
    
    var $uses = false; //per non definire un model

    var $components = array('Permission','Acl'); 
	
	var $result = null;
    
    public function beforeFilter(){
		parent::beforeFilter();
        $this->Auth->allow('getLog','downloadLog','esegui');

    }

    public function index() {
		
    }
	
	private function sessioni() {
		
		$sessions = array();
		
		$path = realpath(session_save_path());
		// print_r($path);die;
		$files = array_diff(scandir($path), array('.', '..'));
		
		foreach ($files as $file)
		{
			$data["search_results"] = file_get_contents($path . '/' . $file);
			$result_string = trim($data["search_results"]);
			print_r($result_string);
		    $sessions[$file] = unserialize($result_string);
		}
		print_r($sessions);die;
		return $sessions;
		
	}
	
	public function downloadLog($file = "error") {
		// print_r(LOGS);
		try {
			header('Content-Type: application/octet-stream');
			header('Content-Disposition: attachment; filename="'.$file.'.log"'); 
			header('Content-Transfer-Encoding: binary');
			// $context  = stream_context_create($opts);
			// $result = file_get_contents($url, false, $context, -1, 40000);
			$fileString = file_get_contents(LOGS.$file.".log");
			if(!$fileString){
				$this->Session->setFlash(__("Impossibile leggere il file di log."),null,null,LOG_ERROR);
			}
			echo $fileString;exit;
			// return $fileString;
		$data=array('esito'=>'ok', 'errore' => '__("Impossibile leggere il file di log.")','log'=>$fileString);
		} catch (exception $ex) {
			$this->Session->setFlash(__("Impossibile leggere il file di log."),null,null,LOG_ERROR);
		}
		// $this->redirect($this->referer());
		// json_encode($data);
	}

	
	public function getLog() {
		
		// per tutte le chiamate imposto l'ajax layout
		$this->layout="ajax";
		$this->autorender = false;
		
    	Controller::loadModel('Log');
		
		$limit = 10; // valore di default
		$offset = 0; // valore di default
		
		// print_r($this->request->query);
		
		if (isset($this->request->query["iDisplayLength"])) {
			$limit = $this->request->query["iDisplayLength"];
		}
		if (isset($this->request->query["iDisplayStart"])) {
			$offset = $this->request->query["iDisplayStart"];
		}
		
		$iTotal =  $this->Log->find("count");

		$contitions = array();
		if(isset($this->request->query["sSearch"]) && !empty($this->request->query["sSearch"])) {
			$searchString=$this->request->query["sSearch"];
			$contitions = array("OR" => array(array('Log.level LIKE' => '%'.$searchString.'%'),array('Log.message LIKE' => '%'.$searchString.'%'),array('Log.session LIKE' => '%'.$searchString.'%')));
		}
			
		// $logs = $this->Log->find("all",array('limit' => $limit, 'offset' => $offset, 'order' => 'Log.id','OR' => array(
		    // array('Log.level LIKE' => '%'.$searchString.'%'),
		    // array('Log.message LIKE' => '%'.$searchString.'%')
		// )));
		$logs = $this->Log->find("all",array('limit' => $limit, 'offset' => $offset, 'order' => 'Log.id DESC', 'conditions' => $contitions));
			
		$iFilteredTotal=$iTotal;
		// $iFilteredTotal=count($logs);
		
		// print_r($logs);die;
		
		$aColumns = array( 'id', 'level', 'session', 'ip', 'message', 'dt_ins' );
	
		/* Indexed column (used for fast and accurate table cardinality) */
		$sIndexColumn = "id";

		$output = array(
			"sEcho" => intval($_GET['sEcho']),
			"iTotalRecords" => $iTotal,
			"iTotalDisplayRecords" => $iFilteredTotal,
			"aaData" => array()
		);
	
		foreach ($logs as $log) {
			$row = array();
			for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
					$row[] = $log["Log"][ $aColumns[$i] ];
			}
			$output['aaData'][] = $row;
		}
		echo json_encode( $output );
		exit();
		
	}
	

	public function refreshPermission() {
		$this->Permission->readPermission();
		$this->redirect("/Info");
	}
	
	public function esegui() {
		try {
			if($this->request->is('ajax') && $this->request->is('post')) {
				$query=$this->request->data["query"];
				// per tutte le chiamate imposto l'ajax layout
				$this->layout="ajax";
				$this->autorender = false;
				//chiamata ajax
		    	Controller::loadModel('Dual');
				$this->result=$this->Dual->query($query);
				// CakeLog::write(LOG_NOTICE,json_encode($this->result));
				echo json_encode($this->result);
				exit();
			} else {
				$this->set("name",__("Non sei abilitato ad accedere a questa pagina, contatta l'Amministratore."));
				$this->set("url",$this->request->url);
				$this->render("/Errors/error400");
				
			}
		} catch (exception $e) {
	    	CakeLog::write(LOG_ERR,$e->getMessage());
			echo new Exception(__("errore in fase di esecuzione della query:"). $e->getMessage());
			exit();
		}
	}

}
?>